/*
 * Copyright (c) 2022, OUXIAOLONG. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.examples.springboot.jpa.repository;

import java.util.Objects;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import com.examples.springboot.jpa.domain.Climber;
import com.examples.springboot.jpa.domain.ClimberPhoneNumber;

// Examples for how to use 'EntityManager'.
public class CustomRepositoryImpl implements CustomRepository {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Climber customFindById(String id) {
      /* JPA Implement */
//    	return entityManager.find(Climber.class, id);

    	/* SELECT * FROM Climber LIMIT 1 OFFSET 1 */
//    	return entityManager.createQuery("Select c From Climber c", Climber.class).setMaxResults(1).setFirstResult(1).getSingleResult();

        return (Climber) entityManager.createQuery("FROM Climber c WHERE c.id = :id LIMIT ?1 OFFSET ?2")
                .setParameter("id", id)
                .setParameter(1, 1)
                .setParameter(2, 1)
                .getSingleResult();
    }

    @PostConstruct
    public void postConstruct() {
        Objects.requireNonNull(entityManager);
    }

    @Override
    @Transactional
    public ClimberPhoneNumber savePhoneNumber(ClimberPhoneNumber phoneNumber) {
      entityManager.persist(phoneNumber);
      return phoneNumber;
    }
}